<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: ml
 * Date: 2017-11-07
 * Time: 16:33
 */

class Quantification extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('M_quantification');
        $this->load->model('M_quantification_Map');
    }
    private $yer = array('1' => '月', '2' => '上线');
    //量化任务列表
    public function ListQuantification()
    {
        if ($this->input->get_post("inajax")) {

            $page = getParam($this->input->get_post("page"), 'int', 1);

            $where = array('is_del' => 1);
            $name = getParam($this->input->get_post("name"), 'string');
            $yer = getParam($this->input->get_post("type"), 'int');//考核周期
            $status = getParam($this->input->get_post("user_work"), 'int');//巡视类别
            $sort_by = getParam($this->input->get_post("sort_by"), 'string', 'quantification_id');
            $sort_order = getParam($this->input->get_post("sort_order"), 'string', 'DESC');
            if ($sort_by == 'name') {
                $sort_by = "CONVERT(name USING gbk)";
            }
            $order = $sort_by . ' ' . $sort_order . ', quantification_id desc';

//            if ($start) {
//                $where['start_time'] = strtotime($start . ' 00:00:00');
//            }

            if ($yer) {
                $where['quantification_check_cycle'] = $yer;
            }
            if ($status) {
                $where['quantification_post_type'] = $status;
            }
            if ($name) {
                $where['search']['like']['quantification_name'] = $name;
            }
//            $mysql = "select qq.quantification_id,qq.quantification_name,qq.quantification_start_time,qq.quantification_check_cycle,qq.quantification_addtime,a.name from
//t_quantification qq LEFT JOIN
//((select q.quantification_id,p.post_name name from t_quantification q LEFT JOIN t_post p on q.quantification_user=p.post_id where quantification_post_type=3)
//UNION
//(select q.quantification_id,u.user_name name from t_quantification q LEFT JOIN t_user u on q.quantification_user=u.user_id where quantification_post_type=1))
// a on qq.quantification_id=a.quantification_id
//";//备注
//            $ll = $this->M_quantification->querylist($mysql);
//            exit(json_encode(array('code'=>0,'data'=>$ll,'info'=>'成功')));
            $per_page = 10; //每一页显示的数量
            $this->load->library("common_page");
            $total = $this->M_quantification->getOne('Count(*)', $where);
            $page_string = $this->common_page->page_string($total, $per_page, $page);
            $limit = ($page - 1) * $per_page;
            $limit = '';
//            $list = $this->M_quantification->getList('*', $where, $per_page, $limit, $order);
            $list = $this->M_quantification->getList('*', $where, $limit, $limit, $order);
            $tables = array('t_quantification_map'=>'q','t_grid'=>'m');
            $join = array('q.grid_id = m.grid_id');
            foreach ($list as $k => &$v) {
                $v['quantification_start_time'] = date('Y-m-d', $v['quantification_start_time']);
                $v['quantification_addtime'] = $v['quantification_updatetime'] == null ? '无更新时间':date('Y-m-d H:i:s', $v['quantification_updatetime']);
                if($v['quantification_post_type'] == 1)//人员
                {//多个人员以逗号分隔开
                    $table = array('t_user'=>'u');
                    $this->load->model('M_user');
                    $v['name'] = $this->M_user->getJoinOne($table,null,"GROUP_CONCAT(DISTINCT u.user_name order by field(u.user_id,$v[quantification_user])) as name" , array("u.user_id IN ($v[quantification_user])"=>null) , null);
                }
                else//岗位
                {
                        $table = array('t_post'=>'p');
                    $this->load->model('M_post');
                    $v['name'] = $this->M_post->getJoinOne($table,null,"GROUP_CONCAT(DISTINCT p.post_name order by field(p.post_id,$v[quantification_user])) as name",array("p.post_id IN ($v[quantification_user])"=>null),null);
                }
                $v['map'] = $this->M_quantification_Map->getJoinList($tables,$join,'q.*,m.*' , array('q.quantification_id'=>$v['quantification_id'],'q.is_del'=>1) , null, null);
                if($v['map'])
                {
                    $v['quantification'] = $v['map'][0]['quantification_task_cycle_d'].'天'.$v['map'][0]['quantification_task_cycle_h'].'时巡视'.$v['map'][0]['quantification_task_number'].'次';
                }
                else
                {
                    $v['quantification'] = '无';
                }
            }

            exit(json_encode(array('code'=>0,'data'=>$list,'info'=>'成功')));
//            exit(result_to_towf_new($list, 1, '成功', $page_string));
        }
        $data['yer_list'] = $this->yer;
        $this->load->view('quantification/quantification.php', $data);
    }
    //查询量化任务
    public function QueryQuantification()
    {
        return;
    }
    //获取人员
    public function GetUser()
    {
        return;
    }
    //获取岗位
    public function GetPost()
    {
        return;
    }
    /**
     @name 添加、修改量化任务
     @2017-11-07
     @author ml
     @param $name 量化任务名称
     @param $start_time 任务生效日期
     @param $user_work_id 类型 //人员ID、岗位ID
     @param $user_work 巡视类别 //1：人员、3：岗位
     @param $type 考核周期 //1:月、2:线上
     @param $map_array 网格配置规则
     **/
    public function AddQuantification()
    {
        /*
         * 【【【【【增加日志】】】】】
         */
        $id = getParam($this->input->get_post("id"), 'int',0);
        if (!empty($_POST)) {
            $arr = $_POST['qu_arrs'];   //任务数组
//        if (true) {
            $i = 0;
            $count = count($arr);
            foreach($arr as $value)
            {
                $data=array();
                if (empty($value['id'])) {
                    $data['quantification_addtime'] = $this->time;
                } else {
                    $data['quantification_id'] = $value['id'];
                    $data['quantification_updatetime'] = $this->time;;
                }
                //基础参数start
                $data['quantification_name'] = $value['name'];   //名称
                $data['quantification_start_time'] = $value['start_time'];  //开始时间
                $data['quantification_check_cycle'] = $value['type'];       //考核周期
                $data['quantification_post_type'] = $value['user_work']; //1 人员 3 岗位
                $data['quantification_user'] = $value['user_work_id'];   //人员
                $data['quantification_type'] = $value['qu_type'];   //1为自定义 2为固定
                $data['is_del'] = 1; //1未删除 2已删除
                $data['quantification_status'] = 1; //1未触发 2触发
                $data['quantification_user'] = explode(',',$data['quantification_user']);
                foreach ($data['quantification_user'] as $key=>$va)
                {
                    if (empty($va))
                    {
                        unset($data['quantification_user'][$key]);
                    }
                }
                $data['quantification_user'] = implode(',',$data['quantification_user']);
                //基础参数end
                //验证
                $y = array('quantification_name', 'quantification_start_time', 'quantification_check_cycle', 'quantification_post_type', 'quantification_user');
                foreach ($y as $v) {
//                if (empty($data[$v])) showMsg('基础配置数据不全,保存失败', '/quantification/index', 2);
                }
                $data['quantification_start_time'] = strtotime($data['quantification_start_time']);
                $map_array = array('0'=>array('map_id'=>'1,2,3','d'=>'1','h'=>'0'),'1'=>array('map_id'=>'4,5,6','d'=>'3','h'=>'0'));
                foreach ($map_array as $k => $v) {
                    if (empty($map_array[$k]['map_id']) && empty($map_array[$k]['d']) && empty($map_array[$k]['h'])) {
                        exit(json_encode(array('code'=>1,'data'=>'','info'=>'网格配置数据不全,保存失败')));
                    }
                }
                if (!is_array($map_array))
                {
                    exit(json_encode(array('code'=>1,'data'=>'错误1','info'=>'数据不全,保存失败')));
                }
                foreach ($data as $key=>$val)
                {
                    if(empty($val))
                    {
                        exit(json_encode(array('code'=>1,'data'=>"错误2:$key 为$val",'info'=>'数据不全,保存失败')));
                    }
                }
                if(!empty($data['quantification_id']))
                {
                    $rid = $this->M_quantification->updateData($data,array('quantification_id'=>$data['quantification_id']));
                    if($rid)
                    {
                        $rid = $data['quantification_id'];
                    }
                    else
                    {
                        exit(json_encode(array('code'=>1,'data'=>"",'info'=>'保存失败')));
                    }
                    $this->M_quantification_Map->updateData(array('is_del' => 2),array('quantification_id'=>$data['quantification_id'],'is_del' => 1));
                }
                else
                {
                    $rid = $this->M_quantification->saveData($data);
                }
                //网格数据start
                $map = array();
                $map_name = $value['map_id'];
                $map['quantification_task_cycle_d'] = $value['d'];
                $map['quantification_task_cycle_h'] = $value['h'];
                $map['quantification_task_number'] = $value['number'];
                $map['quantification_id'] = $rid;
                $map['quantification_task_addtime'] = time();
                $map_name = explode(',',$map_name);
                foreach ($map_name as $v)
                {
                    $map['grid_id'] = $v;
                    foreach ($map as $keys=>$values)
                    {
                        if(empty($values) && $values!=0)
                        {
                            exit(json_encode(array('code'=>1,'data'=>"错误3:$keys 为$values",'info'=>'数据不全,保存失败')));
                        }
                    }
                    $this->M_quantification_Map->saveData($map);
                    if ($this->db->trans_status() === false) {
                        $this->db->trans_rollback();
                    } else {
                        $this->db->trans_commit();
                    }
                }
                //网格数据end
                if ($rid) {
                    $i++;
//                    showMsg('编辑成功', '/quantification/index', 1);
                } else {
//                    showMsg('编辑失败', '/quantification/index', 2);
                }
            }
            if($i == $count)
            {
                exit(json_encode(array('code'=>0,'data'=>'','info'=>'成功')));
            }
            elseif ($i==0)
            {
                exit(json_encode(array('code'=>1,'data'=>'','info'=>'失败')));
            }
            else
            {
                exit(json_encode(array('code'=>2,'data'=>'','info'=>'成功部分')));
            }

        } else {
            if($id == 0)
            {
                exit(json_encode(array('code'=>1,'data'=>'','info'=>'ID不能为0')));
            }
            $where = array(
                'quantification_id' => $id
            );
            $data['list'] = $this->M_quantification->getRow('*', $where);

            if (empty($data['list'])) {
                $data['list'] = array(
                    'id' => '',
                    'name' => '',
                    'start_time' => '',
                    'status' => '',
                    'remark' => '',
                );
            }
            else
            {
                if($data['list']['quantification_post_type'] == 1)//人员
                {//多个人员以逗号分隔开
                    $table = array('t_user'=>'u');
                    $this->load->model('M_user');
                    $user_arr = $data['list']['quantification_user'];
                    $data['list']['quantification_user_name'] = $this->M_user->getJoinOne($table,null,"GROUP_CONCAT(DISTINCT u.user_name order by field(u.user_id,$user_arr)) as name" , array("u.user_id IN ($user_arr)"=>null) , null);
                }
                else//岗位
                {
                    $table = array('t_post'=>'p');
                    $this->load->model('M_post');
                    $user_arr = $data['list']['quantification_user'];
                    $data['list']['quantification_user_name'] = $this->M_post->getJoinOne($table,null,"GROUP_CONCAT(DISTINCT p.post_name order by field(p.post_id,$user_arr)) as name",array("p.post_id IN ($user_arr)"=>null),null);
                }

                $data['list']['quantification_start_time'] = date('Y-m-d', $data['list']['quantification_start_time']);
            }
//            $type = getParam($this->input->get_post("type"), 'int');
//            $url = $type == 1 ? 'quantification/quantification_info.php' : 'quantification/quantification_add.php';
//            $data['yer_list'] = $this->yer;

            //角色
//            $sql = "select Id as id,RoleName as name from t_auth_roles WHERE RoleName NOT like '%普通%' AND RoleName NOT like '%管理员%'";
            //岗位
//            $sql = "select post_id,post_name from t_post";
//            $data['work'] = $this->M_quantification->querylist($sql);

            //网格相关
//            $sql = 'select grid_id,grid_name from t_grid ';
//            $data['map'] = $this->M_quantification->querylist($sql);
            $tables = array('t_quantification_map'=>'q','t_grid'=>'m');
            $join = array('q.grid_id = m.grid_id');
            $data['map'] = $this->M_quantification_Map->getJoinRow($tables,$join,'q.*,GROUP_CONCAT(DISTINCT m.grid_name) AS map_name,GROUP_CONCAT(DISTINCT m.grid_id) AS map_id' , array('q.quantification_id'=>$id,'q.is_del'=>1) , null, '1');

            exit(json_encode(array('code'=>0,'data'=>$data,'info'=>'成功')));
        }
    }
    //获取所有网格
    public function GetMapAll()
    {

    }
    //删除量化任务(逻辑删除)
    public function DeleteQuantification()
    {
        /*
         * 【【【【【增加日志】】】】】
         */
        $id = $_POST['id'];
        //需要检查相应权限是否可以删除
        if(count($id)==0)
        {
            exit(json_encode(array('code'=>1,'data'=>'','info'=>'参数异常')));
        }
        $id = implode(',',$id);
        $sql = "UPDATE t_quantification SET is_del=2 WHERE quantification_id IN($id)";//返回修改行数
//        $sel_sql = "SELECT quantification_user_id FROM t_quantification_user WHERE quantification_id IN($id)";//返回修改行数
//        $sel_res = $this->M_quantification->querylist($sel_sql);
//        foreach ($sel_res as $value)
//        {
//            $sql1 = "UPDATE t_quantification_user_map SET is_del=2 WHERE quantification_user_id=$value[quantification_user_id]";//返回修改行数
//            $this->M_quantification->update_data($sql1);
//        }
        $sql2 = "UPDATE t_quantification_user SET quantification_user_status=2 WHERE quantification_id IN($id)";//返回修改行数
        $res2 = $this->M_quantification->update_data($sql2);
        $res = $this->M_quantification->update_data($sql);
        if($res>0)
        {
            exit(json_encode(array('code'=>0,'data'=>$res,'info'=>'成功')));
        }
        else
        {
            exit(json_encode(array('code'=>1,'data'=>$res,'info'=>'失败')));
        }
    }
}